<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>房屋编号：<el-input placeholder="请输入内容" v-model="queryData.houseNumber" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>承租人姓名：<el-input placeholder="请输入内容" v-model="queryData.lesseeName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>证件号码：<el-input placeholder="请输入内容" v-model="queryData.lesseeIdCard" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>出租用途：
              <el-select v-model="queryData.rentalUse" placeholder="请选择出租用途" filterable clearable>
                <el-option v-for="item in rentalUseTypeOption" :key="item.id" :value="item.code" :label="item.name"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows"
                     v-on:checkSingleRow="checkSingleRow"
                     v-on:changeSingleRow="changeSingleRow"
                     v-on:deleSingleRow="deleSingleRow" />
          <el-dialog :title="dialogTitle"
                     :visible.sync="dialogFormVisible"
                     :before-close="close"
                     :close-on-click-modal="false">
            <el-form :model="formData"
                     :rules="rules"
                     ref="formData"
                     :disabled="showOnly"
                     label-width="135px"
                     label-height='37px'
                     size="mini">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="网格" prop="allGridIdArr">
                    <div class="block">
                      <el-cascader placeholder="请选择"
                        :options="treeOption"
                        filterable
                        clearable
                        :props="gridIdProps"
                        v-model="formData.allGridIdArr"
                        @change="handleGridCascader">
                      </el-cascader>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="showInput === 0 || showInput === 1">
                  <el-form-item label="所属小区" prop="communityId"
                      :rules="!formData.courtyardId?[{required:true,message: '请选择小区', trigger: 'blur'}]:[{required:false,message: '请选择小区', trigger: 'blur'}]">
                    <el-select filterable :disabled="showSpecial" no-data-text="请选择" v-model="formData.communityId"
                      placeholder="请选择所属小区"
                      @change="getBuildingData">
                      <el-option v-for="item in communityData" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="showInput === 0 || showInput === 1">
                  <el-form-item label="所属楼栋" prop="buildingId"
                    :rules="!formData.courtyardId?[{required:true,message: '请选择楼栋', trigger: 'blur'}]:[{required:false,message: '请选择楼栋', trigger: 'blur'}]">
                    <el-select filterable
                      :disabled="showSpecial"
                      no-data-text="请选择"
                      placeholder="请选择所属楼栋"
                      v-model="formData.buildingId"
                      @change="getUnitData">
                      <el-option v-for="item in buildingData" :key="item.id" :value="item.id" :label="item.buildingName"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="showInput === 0 || showInput === 1">
                  <el-form-item label="所属单元" prop="unitId"
                    :rules="!formData.courtyardId?[{required:true,message: '请选择单元', trigger: 'blur'}]:[{required:false,message: '请选择单元', trigger: 'blur'}]">
                    <el-select filterable
                      :disabled="showSpecial"
                      no-data-text="请选择"
                      v-model="formData.unitId"
                      placeholder="请选择所属单元"
                      @change="getHouseData">
                      <el-option v-for="item in unitList"
                        :key="item.id"
                        :value="item.id"
                        :label="item.unitName"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12"
                  v-if="showInput === 0 || showInput === 1">
                  <el-form-item label="房屋" prop="houseId"
                    :rules="!formData.courtyardId?[{required:true,message: '请选择房屋', trigger: 'blur'}]:[{required:false,message: '请选择房屋', trigger: 'blur'}]">
                    <el-select filterable
                      :disabled="showSpecial"
                      clearable
                      v-model="formData.houseId"
                      placeholder="请选择房屋"
                      @change="getFloorNumber"
                      @clear='clearFloorNumber'>
                      <el-option v-for="item in houseData" :key="item.id" :value="item.id" :label="item.houseNumber"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="showInput === 0 || showInput === 2">
                  <el-form-item label="院落"
                    prop="courtyardId"
                    :rules="(!formData.houseId||!formData.unitId||!formData.buildingId||!formData.communityId)?[{required:true,message: '请选择院落',trigger: 'blur'}]:[{required:false,message: '请选择院落',trigger: 'blur'}]">
                    <el-select filterable
                               clearable
                               :disabled="showCourtyard"
                               v-model="formData.courtyardId"
                               placeholder="请选院落"
                               @change="getCourtyardId"
                               @clear='clearCourtyard'>
                      <el-option v-for="item in courtyardData"
                                 :key="item.id"
                                 :value="item.id"
                                 :label="item.courtyardNo"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="房屋地址"
                                prop="houseAddr">
                    <el-input v-model="formData.houseAddr"
                              readonly
                              placeholder="房屋地址"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="建筑面积"
                                prop="buildingArea">
                    <el-input v-model="formData.buildingArea"
                              readonly
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="建筑用途"
                                prop="buildingUse">
                    <el-select filterable
                               readonly
                               v-model="formData.buildingUse"
                               placeholder="请选择建筑用途">
                      <el-option v-for="item in dictData.buildUseType"
                                 :key="item.id"
                                 :value="item.code"
                                 :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="房主姓名"
                                prop="homeownerName">
                    <el-input v-model="formData.homeownerName"
                              readonly
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件代码"
                                prop="certificateCode">
                    <el-select filterable
                               v-model="formData.certificateCode"
                               placeholder="证件代码">
                      <el-option v-for="item in ideferCodeData"
                                 :key="item.code"
                                 :value="item.code"
                                 :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件号码"
                                prop="homeownerIdCard">
                    <el-input v-model="formData.homeownerIdCard"
                              readonly
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="房主联系方式"
                                prop="homeownerPhone">
                    <el-input v-model="formData.homeownerPhone"
                              readonly
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="房主现住地详址"
                                prop="homeownerLiveAddr">
                    <el-input v-model="formData.homeownerLiveAddr"
                              readonly
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出租用途"
                                prop="rentalUse">
                    <el-select filterable
                               v-model="formData.rentalUse"
                               placeholder="请选择出租用途">
                      <el-option v-for="item in rentalUseTypeOption"
                                 :key="item.id"
                                 :value="item.code"
                                 :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="隐患类型"
                                prop="dangerType">
                    <el-select filterable
                               v-model="formData.dangerType"
                               placeholder="请选择隐患类型">
                      <el-option v-for="item in dictData.dangerType"
                                 :key="item.id"
                                 :value="item.code"
                                 :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="承租人身份证号码"
                                prop="lesseeIdCard">
                    <el-input v-model="formData.lesseeIdCard"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="承租人姓名"
                                prop="lesseeName">
                    <el-input v-model="formData.lesseeName"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="承租人联系方式"
                                prop="lesseePhone">
                    <el-input v-model="formData.lesseePhone"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="选择经纬度"
                                prop="longitude">
                      <el-col :span="8">
                        <el-input v-model="formData.longitude"
                                  :disabled="true"
                                  placeholder="经度"></el-input>
                      </el-col>
                      <el-col :span="1"
                              style="text-align: center">-</el-col>
                      <el-col :span="7">
                        <el-input v-model="formData.latitude"
                                  :disabled="true"
                                  placeholder="纬度"></el-input>
                      </el-col>
                      <el-col :span="8">
                        <el-button type="text"
                                  @click="openSimpleMap">从地图选择</el-button>
                      </el-col>
                    </el-form-item>
                </el-col>
              </el-row>

            </el-form>
            <div v-if="!showOnly"
                 slot="footer"
                 class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary"
                         @click="save">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog class="dialog-body-mini"
                     :visible.sync="showMap"
                     title="选择经纬度"
                     width="70%"
                     top="8vh"
                     :before-close="mapCancel">
            <edit-map v-if="showMap"
                      :mode="mapMode"
                      @appMapCallback="appMapCallback"
                      :target="mapTarget"></edit-map>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>
<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import GridCascader from '@/components/GridCascader'
import DictDataUtil from '@/utils/DictDataUtil'
import EditMap from '@/components/EditMap'
import { createMapLocation, updateMapLocation } from '@/http/AppApi'
import { getUserGridTree } from '@/utils/SessionDataUtil'
import { getLastIdByAllId, isCommonDo, getCaseAllGridIdByGridTreeData } from '@/utils/CommonUtil'
import { findRentalHouse, createRentalHouse, findCommunityList, findCourtyardList,
  deleteRentalHouse, updateRentalHouse, findHouseList,
  findUnitList, findBuildingList, getHouse, getRentalHouse, getCourtyard, getBuilding} from '@/http/FangWuGuanLiApi'
import { validatePhone, validateIdefer } from '@/utils/validate'
import { getDictDataOption } from '@/utils/getDictDataOption'
import { getAllRegion, getAllRegionObj } from '@/utils/region'
export default {
  data () {
    return {
      tableData: [],
      pageData: {},
      formData: {},
      address: {
        address: '',
        buildingName: '',
        area: '',
        unitName: '',
        floorNumber: '',
        houseNumber: '',
        temp1: '',
        temp2: '',
        temp3: ''
      },
      queryData: {},
      allGridData: [],
      treeData: [],
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      treeOption: [],
      ideferCodeData: [],
      dialogTitle: '',
      dialogFormVisible: false,
      mapHackReset: false,
      showMap: false,
      showInput: 0,
      mapMode: 'simple',
      mapTarget: {},
      currentSelectedData: [],
      showOnly: false,
      showSpecial: false,
      showCourtyard: false,
      dictData: {},
      tableColumns: [
        { prop: 'houseNumber', label: '房屋编号' },
        { prop: 'houseAddr', label: '房屋地址' },
        { prop: 'buildingUse', label: '建筑用途', formatter: this.filterBuildUse },
        { prop: 'buildingArea', label: '建筑面积(m²)' },
        { prop: 'lesseeName', label: '承租人姓名' },
        { prop: 'lesseeIdCard', label: '承租人身份证号' },
        { prop: 'lesseePhone', label: '承租人手机号' }
      ],
      houseData: [],
      buildingData: [],
      unitList: [],
      communityData: [],
      courtyardData: [],
      rules: {
        allGridIdArr: [{
          required: true,
          message: '选择网格',
          trigger: 'blur'
        }],
        longitude: [{
          required: true,
          message: '请填写经纬度',
          trigger: 'blur'
        }],
        latitude: [{
          required: true,
          message: '请填写经纬度',
          trigger: 'blur'
        }],
        // communityId: [{
        //   required: true,
        //   message: '请选择所属小区',
        //   trigger: 'change'
        // }],
        // buildingId: [{
        //   required: true,
        //   message: '请选择所属楼栋',
        //   trigger: 'change'
        // }],
        // unitId: [{
        //   required: true,
        //   message: '请选择所属单元',
        //   trigger: 'change'
        // }],
        // houseId: [{
        //   required: true,
        //   message: '请选择房屋编号',
        //   trigger: 'change'
        // }],
        // courtyardId: [{
        //   required: true,
        //   message: '请选择院落',
        //   trigger: 'change'
        // }],
        houseAddr: [{
          required: true,
          message: '房屋地址',
          trigger: 'blur'
        }],
        buildingUse: [{
          required: true,
          message: '请选择建筑用途',
          trigger: 'blur'
        }],
        buildingArea: [{
          required: true,
          message: '请输入建筑面积',
          trigger: 'blur'
        }],
        homeownerName: [{
          required: true,
          message: '请输入房主姓名',
          trigger: 'blur'
        }],
        certificateCode: [{
          required: true,
          message: '请选择证件类型',
          trigger: 'blur'
        }],
        homeownerIdCard: [{
          required: true,
          message: '请输入证件号码',
          trigger: 'blur'
        }],
        homeownerPhone: [{
          required: true,
          validator: validatePhone,
          message: '请输入手机号',
          trigger: 'blur'
        }],
        homeownerLiveAddr: [{
          required: true,
          message: '房主现住地详址',
          trigger: 'blur'
        }],
        rentalUse: [{
          required: true,
          message: '请选择出租用途',
          trigger: 'blur'
        }],
        dangerType: [{
          required: true,
          message: '请选择隐患类型',
          trigger: 'blur'
        }],
        lesseeIdCard: [{
          required: true,
          validator: validateIdefer,
          message: '请输入承租人身份证号码',
          trigger: 'blur'
        }],
        lesseeName: [{
          required: true,
          message: '请输入承租人姓名',
          trigger: 'blur'
        }],
        lesseePhone: [{
          required: true,
          message: '请输入承租人联系方式',
          trigger: 'blur'
        }]
      },
      rentalUseTypeOption: []
    }
  },
  components: {
    EditMap,
    AppTree,
    BtnGroup,
    AppTable,
    GridCascader
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
    this.ideferCodeData = getDictDataOption('证件代码')
    this.dictData.buildUseType = getDictDataOption('建筑用途')
    this.rentalUseTypeOption = getDictDataOption('出租用途')
  },
  methods: {
    filterBuildUse (row, column) {
      let buildingUseName = ''
      for (let i = 0; i < this.dictData.buildUseType.length; i++) {
        const element = this.dictData.buildUseType[i]
        if (element.code === row.buildingUse) {
          buildingUseName = element.name
          break
        }
      }
      return buildingUseName
    },
    save () {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (this.formData) {
            if (!this.beforeSubmit()) {
              return
            }
            if (this.formData.id) {
              updateRentalHouse(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.dialogFormVisible = false
                  this.getTableData()
                  this.cancel('formData')
                  this.$message({
                    type: 'success',
                    message: '修改成功'
                  })
                }
              })
            } else {
              createRentalHouse(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.dialogFormVisible = false
                  this.getTableData()
                  this.cancel('formData')
                  this.$refs['formData'].resetFields()
                  this.$message({
                    type: 'success',
                    message: '添加成功'
                  })
                }
              })
            }
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteRentalHouse(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel (formName) {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs[formName].resetFields()
    },
    close () {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    getTableData () {
      let param = this.queryData
      findRentalHouse(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            this.dictData.buildUseType = getDictDataOption('建筑用途')
            for (let i = 0; i < data.items.length; i++) {
              for (let j = 0; j < this.dictData.buildUseType.length; j++) {
                if (data.items[i].buildingUse === this.dictData.buildUseType[j].id) {
                  data.items[i].buildingUse = this.dictData.buildUseType[j].name
                }
              }
            }
            isCommonDo(this.pageData, this)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
        this.treeOption = data
      }
    },
    beforeSubmit () {
      if (this.formData.allGridId) {
        if (this.formData.allGridIdArr && this.formData.allGridIdArr.length !== 0) {
          let liveIndex = this.formData.allGridIdArr.length - 1
          let liveData = {}
          liveData.id = this.formData.allGridIdArr[liveIndex]
          liveData.items = this.treeData
          liveData.isGetAllId = true
          this.formData.allGridId = getAllRegion(liveData)
        } else {
          this.formData.allGridId = ''
        }
        this.formData.gridId = getLastIdByAllId(this.formData.allGridId)
      }
      return true
    },
    getDictData () {
      this.dictData.dangerType = DictDataUtil.getDangerType()
      this.dictData.buildUseType = DictDataUtil.getBuildingType()
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
        this.showInput = 0
        this.showCourtyard = false
        this.showSpecial = false
        this.getDictData()
        if (callbackData.btnType === 'post') {
          this.formData = this.formData.allGridId ? this.formData : {}
        } else {
          let tempData = {}
          for (const key in callbackData.rows[0]) {
            if (callbackData.rows[0].hasOwnProperty(key)) {
              tempData[key] = callbackData.rows[0][key]
            }
          }
          this.formData = tempData
          let regionData = {}
          regionData.id = this.formData.gridId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'allGridIdArr', gridIdArr)
          this.address.address = ''
          getRentalHouse(callbackData.rows[0].id).then(resp => {
            if (resp.code && resp.code === '200') {
              let data = resp.data
              if (!data.courtyardId) {
                this.showInput = 1
                this.getHouseDetailData(data.houseId)
              } else {
                this.formData.communityId = ''
                this.formData.buildingId = ''
                this.formData.unitId = ''
                this.formData.houseId = ''
                this.showInput = 2
                let regionData = {}
                regionData.id = this.formData.gridId
                regionData.items = this.treeData
                let temp = getAllRegionObj(regionData)
                this.address.address = ''
                for (let i = 0; i < temp.length; i++) {
                  const element = temp[i]
                  this.address.address += element.name + ' '
                }
                findCourtyardList({ likeAllGridId: this.formData.gridId }).then(resp => {
                  if (resp.code && resp.code === '200') {
                    let data = resp.data
                    if (data && data instanceof Array) {
                      this.courtyardData = data
                      // console.log(data)
                      this.courtyardData.find((item) => {
                        if (item.id === this.formData.courtyardId) {
                          this.address.area = item.courtyardNo
                        }
                      })
                    }
                  }
                })
                this.$set(this.formData, 'courtyardId', data.courtyardId)
                this.$set(this.formData, 'certificateNumber', data.certificateNumber)
                this.$set(this.formData, 'homeownerLiveAddr', data.homeownerLiveAddr)
                this.$set(this.formData, 'latitude', data.latitude)
                this.$set(this.formData, 'longitude', data.longitude)
              }
            }
          })
        }
      }
    },
    checkSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    changeSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    deleSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else {
        this.currentSelectedData = []
      }
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.gridId = data.id
      this.getTableData()
      this.formData.allGridId = getCaseAllGridIdByGridTreeData(data)
      this.formData.allGridIdArr = this.formData.allGridId.split(',')
    },
    // 检索按钮操作
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    getHouseData (unitId) {
      // 根据单元和楼栋查询房屋
      let param = { unitId: unitId }
      findHouseList(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            this.houseData = data
          }
        }
      })
      if (unitId) {
        if (this.communityData && this.communityData instanceof Array && this.communityData.length > 0) {
          if (this.unitList && this.unitList instanceof Array && this.unitList.length > 0) {
            this.unitList.find((item) => {
              if (item.id === unitId) {
                this.address.unitName = item.unitName + ' '
              }
            })
            this.$set(this.formData, 'houseAddr', this.address.address + this.address.area + this.address.buildingName + this.address.unitName + this.address.houseNumber)
          }
        }
      }
    },
    getUnitData (data) {
      if (data) {
        let param = { buildingId: data }
        findUnitList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            this.unitList = data
          }
        })
        if (data && this.buildingData.length > 0) {
          this.buildingData.find((item) => {
            if (item.id === data) this.address.buildingName = item.buildingName + ' '
          })
          this.$set(this.formData, 'houseAddr', this.address.address + this.address.area + this.address.buildingName + this.address.unitName + this.address.houseNumber)
        }
      }
    },
    getCommunityData (gridId) {
      if (gridId && gridId !== '') {
        let param = { likeAllGridId: gridId }
        findCommunityList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data && data instanceof Array) {
              this.communityData = data
              if (this.communityData.length === 0) {
                this.formData.communityId = ''
                this.formData.buildingId = ''
                this.formData.unitId = ''
                this.formData.houseId = ''
              }
            }
          }
        })
        findCourtyardList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data && data instanceof Array) {
              this.courtyardData = data
              if (this.courtyardData.length === 0) {
                this.formData.courtyardId = ''
              }
            }
          }
        })
      }
    },
    handleGetCommunityData (allGridId) {
      if (allGridId && allGridId !== '') {
        let arr = allGridId
        if (arr && arr.length > 0) {
          let gridId = arr[arr.length - 1]
          this.getCommunityData(gridId)
        }
      }
    },
    getBuildingData (communityId) {
      if (communityId && communityId !== '') {
        let param = { communityId: communityId }
        findBuildingList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data && data instanceof Array) {
              this.buildingData = data
            }
          }
        })
        if (this.communityData && this.communityData instanceof Array && this.communityData.length > 0) {
          this.communityData.find((item) => {
            if (item.id === communityId) this.address.area = item.name + ' '
          })
          this.$set(this.formData, 'houseAddr', this.address.address + this.address.area + this.address.buildingName + this.address.unitName + this.address.houseNumber)
        }
      }
    },
    handleGridCascader (data) {
      if (data && data !== '') {
        this.communityData = []
        this.handleGetCommunityData(data)
        let arr = data
        let regionData = {}
        regionData.id = arr[arr.length - 1]
        regionData.items = this.treeData
        let temp = getAllRegionObj(regionData)
        this.address.address = ''
        for (let i = 0; i < temp.length; i++) {
          const element = temp[i]
          this.address.address += element.name + ','
        }
        this.$set(this.formData, 'houseAddr', this.address.address + this.address.area + this.address.buildingName + this.address.unitName)
      }
    },
    getHouseDetailData (houseId) {
      if (houseId && houseId !== '') {
        getHouse(houseId).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data) {
              // this.formData = data
              this.$set(this.formData, 'buildingId', data.buildingId)
              this.$set(this.formData, 'unitId', data.unitId)
              this.$set(this.formData, 'communityId', data.communityId)
              this.$set(this.formData, 'houseId', data.id)
              this.$set(this.formData, 'homeownerLiveAddr', data.homeownerLiveAddr)
              this.$set(this.formData, 'homeownerIdCard', data.homeownerIdCard)
              this.$set(this.formData, 'latitude', data.latitude)
              this.$set(this.formData, 'longitude', data.longitude)
              this.$set(this.formData, 'certificateCode', data.certificateCode)
              getBuilding(data.buildingId).then(resp => {
                if (resp.code && resp.code === '200') {
                  let data = resp.data
                  this.$set(this.formData, 'buildingUse', data.buildingType)
                }
              })
              let regionData = {}
              console.log(this.formData)
              regionData.id = this.formData.gridId
              regionData.items = this.treeData
              let temp = getAllRegionObj(regionData)
              this.address.address = ''
              for (let i = 0; i < temp.length; i++) {
                const element = temp[i]
                this.address.address += element.name + ' '
              }
              findCommunityList({ likeAllGridId: this.formData.gridId }).then(resp => {
                if (resp.code && resp.code === '200') {
                  let data = resp.data
                  if (data && data instanceof Array) {
                    this.communityData = data
                    this.communityData.find((item) => {
                      if (item.id === this.formData.communityId) this.address.area = item.name + ' '
                    })
                  }
                }
              })
              findBuildingList({ communityId: this.formData.communityId }).then(resp => {
                if (resp.code && resp.code === '200') {
                  let data = resp.data
                  if (data && data instanceof Array) {
                    this.buildingData = data
                    this.buildingData.find((item) => {
                      if (item.id === this.formData.buildingId) this.address.buildingNum = item.buildingName + ' '
                    })
                  }
                }
              })
              findUnitList({ buildingId: this.formData.buildingId }).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.unitList = resp.data
                  this.unitList.find((item) => {
                    if (item.id === this.formData.unitId) this.address.unitName = item.unitName + ' '
                  })
                }
              })
              findHouseList({ unitId: this.formData.unitId }).then(resp => {
                if (resp.code && resp.code === '200') {
                  let data = resp.data
                  if (data && data instanceof Array) {
                    this.houseData = data
                    this.houseData.find((item) => {
                      if (item.id === this.formData.houseId) this.address.houseNumber = item.houseNumber + ''
                    })
                  }
                }
              })
            }
          }
        })
      }
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        if (appMapInfo.target.targetId) {
          let mapLocation = {}
          if (appMapInfo.poly && appMapInfo.poly instanceof Array && appMapInfo.poly.length > 0) {
            let length = appMapInfo.poly.length
            this.saveMapLocationInfoByArray(0, length, appMapInfo)
          } else {
            mapLocation = this.appMapInfo2MapLocation(appMapInfo)
            this.saveMapLocationInfo(mapLocation)
          }
        } else {
          this.showOnly = false
          this.showMap = false
          this.$set(this.formData, 'latitude', appMapInfo.lnglat.lat)
          this.$set(this.formData, 'longitude', appMapInfo.lnglat.lng)
        }
      }
      return ''
    },
    appMapInfo2MapLocation (appMapInfo) {
      let mapLocation = {}
      mapLocation.targetId = appMapInfo.target.targetId
      mapLocation.targetType = appMapInfo.target.targetType

      if (!appMapInfo.poly) {
        mapLocation.mapArea = appMapInfo.polyPathArr
        mapLocation.mapColor = appMapInfo.polyColor
        // 地图信息id存在则不允许修改targetId和targetType
        if (appMapInfo.id) {
          mapLocation.id = appMapInfo.id
          delete mapLocation.targetId
          delete mapLocation.targetType
        }
      }
      if (appMapInfo.clearStatus) {
        mapLocation.clearStatus = appMapInfo.clearStatus
      }
      if (appMapInfo.markPosition) {
        mapLocation.longitude = appMapInfo.markPosition.lng
        mapLocation.latitude = appMapInfo.markPosition.lat
      }
      return mapLocation
    },
    saveMapLocationInfoByArray (i, length, appMapInfo) {
      if (i >= length) {
        return
      }
      let mapLocation = {}
      mapLocation = this.appMapInfo2MapLocation(appMapInfo)
      mapLocation.mapArea = appMapInfo.poly[i].polyPathArr
      mapLocation.mapColor = appMapInfo.poly[i].polyColor
      mapLocation.id = appMapInfo.poly[i].id
      if (mapLocation.id) {
        delete mapLocation.targetId
        delete mapLocation.targetType
      }
      i++
      let data = mapLocation
      console.log('maplocation id = ' + mapLocation.id)
      if (mapLocation.id) {
        updateMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      }
    },
    saveMapLocationInfo (mapLocation) {
      if (mapLocation.id) {
        updateMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
          }
        })
      }
      this.mapCancel()
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    getFloorNumber (value) {
      if (value) {
        this.houseData.find((item) => {
          if (item.id === value) this.address.houseNumber = item.houseNumber
        })
        this.$set(this.formData, 'houseAddr', this.address.address + this.address.area + this.address.buildingName + this.address.unitName + this.address.houseNumber)
        getHouse(value).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            this.$set(this.formData, 'homeownerName', data.homeownerName)
            this.$set(this.formData, 'buildingArea', data.houseArea)
            this.$set(this.formData, 'homeownerIdCard', data.homeownerIdCard)
            this.$set(this.formData, 'homeownerPhone', data.homeownerPhone)
            this.$set(this.formData, 'homeownerLiveAddr', data.homeownerLiveAddr)
            this.$set(this.formData, 'latitude', data.latitude)
            this.$set(this.formData, 'longitude', data.longitude)
            this.$set(this.formData, 'certificateCode', data.certificateCode)
            this.formData.houseNumber = this.address.houseNumber
            this.showCourtyard = true
            this.formData.courtyardId = ''
            getBuilding(data.buildingId).then(resp => {
              if (resp.code && resp.code === '200') {
                let data = resp.data
                console.log(data)
                this.$set(this.formData, 'buildingUse', data.buildingType)
              }
            })
          }
        })
      }
    },
    getCourtyardId (value) {
      getCourtyard(value).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.$set(this.formData, 'homeownerName', data.homeownerName)
          this.$set(this.formData, 'buildingArea', data.area)
          this.$set(this.formData, 'buildingUse', data.houseUse)
          this.$set(this.formData, 'homeownerIdCard', data.homeownerIdCard)
          this.$set(this.formData, 'homeownerPhone', data.homeownerPhone)
          this.$set(this.formData, 'homeownerLiveAddr', data.homeownerLiveAddr)
          this.$set(this.formData, 'latitude', data.latitude)
          this.$set(this.formData, 'longitude', data.longitude)
          this.showSpecial = true
          this.formData.communityId = ''
          this.formData.buildingId = ''
          this.formData.unitId = ''
          this.address.area = data.courtyardNo
          this.formData.houseNumber = data.courtyardNo
          this.$set(this.formData, 'houseAddr', this.address.address + this.address.area)
        }
      })
    },
    clearCourtyard () {
      this.showSpecial = false
    },
    clearFloorNumber () {
      this.showCourtyard = false
    }
  },
  computed: {},
  watch: {}
}
</script>

<style scoped>
.el-form >>> .el-form-item__error {
  margin-top: 2px;
}
.el-form >>> .el-input__inner {
  height: 37px;
}
.el-form >>> .el-form-item__label {
  line-height: 37px;
}
.el-form >>> .el-cascader__label {
  line-height: 37px;
}
</style>
